var VisualConst = function() {}

var ____clientStaticData = {};
var ____clientDeviceId = "";
var ____clientDeviceInfo = {};
var ____serverInfo = {};


VisualConst.getCustomDevice = function() {
	//先读取页面缓存，再读取本地存储的 deviceid
	if (plus.device.uuid) {
		____clientDeviceId = plus.device.uuid;
	} else if (plus.device.imei) {
		____clientDeviceId = plus.device.imei;
	} else if (plus.device.imsi) {
		if (plus.device.imsi && plus.device.imsi.length > 0) {
			____clientDeviceId = plus.device.imsi[0];
		} else {
			____clientDeviceId = "";
		}
	} else {
		____clientDeviceId = "";
	}
	return {
		"deviceid": ____clientDeviceId.replace(",", "@"),
		"platform": "android",
		"displaysize": VisualConst.getScreenSize(),
		"appid":VisualConst.getAppCfg()['comm']['appid']
	};
}

VisualConst.getMemory = function(cb) {
	cb({"m":1});
}
VisualConst.getClientStaticData = function(cb) {
	//获得设备的mac地址，并且写入到本地，作为设备的id
	if (JSON.stringify(____clientStaticData) != "{}") {
		cb(____clientStaticData);
	} else {
		var data = {};
		data["_customDevice"] = VisualConst.getCustomDevice();
		data["os"] = plus.os;
		data["device"] = plus.device;
		data["networkinfo"] = {
			"currentType": plus.networkinfo.getCurrentType(),
			"all": plus.networkinfo,
			"address": VisualConst.getNetWork()
		}
		____clientStaticData = data;
		____clientDeviceInfo = {
			"id": ____clientDeviceId.replace(",", "@"),
			"ip": ____clientStaticData["networkinfo"]["address"]["deviceip"],
		};
		cb(____clientStaticData);
	}
}
VisualConst.getAppCfg = function() {
	//获得设备的mac地址，并且写入到本地，作为设备的idnpm
	return __config;
}
VisualConst.saveAppCfg = function(cfg) {
	//获得设备的mac地址，并且写入到本地，作为设备的id
	// fs.writeFileSync('./client/conf/cfg.ini',ini.stringify(cfg));
}
// fs.writeFileSync('./client/conf/cfg.ini',ini.stringify(config,{section:'section'}));

VisualConst.getScreenSize = function() {
	const screenSize = plus.screen;
	return screenSize
}
VisualConst.getScreenType = function () {
	var s = 'h';
	if(window.screen.width>window.screen.height){
		s= 'h';
	}else{
		s= 'v';
	}
	return s;
}

VisualConst.getNetWork = function() {
	var mac = "xxx-xxx-xxx-xxx";
	if (plus.os.name == "Android") {
		var Context = plus.android.importClass("android.content.Context");
		var WifiManager = plus.android.importClass("android.net.wifi.WifiManager");
		var wifiManager1 = plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);
		var WifiInfo = plus.android.importClass("android.net.wifi.WifiInfo");
		var wifiInfo1 = wifiManager1.getConnectionInfo();
		var ipAddress = wifiInfo1.getIpAddress();
		
		var deviceIp = '';  
		if (ipAddress != 0) {  
			deviceIp = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));  
		} 
		// console.log("wifiInfo1",deviceIp);
		mac = wifiInfo1.getMacAddress();
		return {
			"deviceip":deviceIp,
			"devicemac":mac
		};
	}
	return {};
}

VisualConst.appendDeviceParam = function (url) {
	if(!url)
		return url;
	var locationId = "";
	var _clientid = "";
	var _clientip = "";
	if(____clientDeviceInfo){
		locationId = ____clientDeviceInfo["locationId"] ||"";
		_clientid = (____clientDeviceInfo["id"]||"");
		_clientip = (____clientDeviceInfo["ip"]||"");
	}
		
	url = url.replace("$locationId$",locationId);
	url = url.replace("$_clientid$",_clientid);
	url = url.replace("$_clientip$",_clientip);
	if(url.indexOf("?")>0){
		url = url + "&_locationId=" + locationId + "&_clientip=" + _clientip + "&_clientid=" + _clientid ;
	}else{
		url = url + "?_locationId=" + locationId + "&_clientip=" + _clientip + "&_clientid=" + _clientid ;
	}
	return url;
}

/**
 * 图片压缩，默认同比例压缩
 * @param {Object} path    
 *         pc端传入的路径可以为相对路径，但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 *         obj 对象 有 width， height， quality(0-1)
 * @param {Object} callback
 *         回调函数有一个参数，base64的字符串数据
 */
function dealImage(path, obj, callback){
    var img = new Image();
    img.src = path;
    img.onload = function(){
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;
            w = obj.width || w;
            h = obj.height || (w / scale);
        var quality = 0.7;        // 默认图片质量为0.7
        
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
              
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if(obj.quality && obj.quality <= 1 && obj.quality > 0){
            quality = obj.quality;
        }
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality );
        // 回调函数返回base64的值
        callback(base64);
    }
}
VisualConst.clientDesktopCapturer = function(options, cb) {
	var bitmap = new plus.nativeObj.Bitmap(new Date().getTime());
	// 将webview内容绘制到Bitmap对象中
	var topWv = plus.webview.getTopWebview();
	topWv.draw(bitmap,function(){
		console.log('截屏绘制图片成功');
		var base64data = bitmap.toBase64Data();
		bitmap.clear();
		console.log(base64data.length);
		dealImage(base64data,{"width":640},cb);
	},function(e){
		bitmap.clear();
		console.log('截屏绘制图片失败：'+JSON.stringify(e));
		cb(null);
	});
}

VisualConst.____renderSysinfo = function(staticdata) {
	var sysinfo = "<table>";
	var s = VisualConst.getScreenSize();
	sysinfo += "<tr><td>screen</td><td>" + s.width + "x" + s.height + "</td></tr>";
	for (var key in staticdata["system"]) {
		sysinfo += "<tr><td>" + key + "</td><td>" + staticdata["system"][key] + "</td></tr>";
	}
	sysinfo += "</table>";
	return sysinfo;
}
VisualConst.getServerInfo = function (){
	// console.log("Lib.getStorage('serverInfo')",null==Lib.getStorage('serverInfo'));
	return JSON.parse(Lib.getStorage('serverInfo') || "{}");
}
VisualConst.setServerInfo = function (info){
	Lib.setStorage('serverInfo',JSON.stringify(info));
}

VisualConst.getLastContent = function (){
	return JSON.parse(Lib.getStorage('lastList') || "{}");
}
VisualConst.setLastContent = function (list){
	Lib.setStorage('lastList',JSON.stringify(list));
}
